package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.Exception.MyException;
import com.itheima.health.dao.MenuDao;
import com.itheima.health.dao.UserDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.pojo.Menu;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import com.itheima.health.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *
 * </p>
 *
 * @author: Eric
 * @since: 2020/11/29
 */
@Service(interfaceClass = UserService.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private MenuDao menuDao;

    /**
     * 通过用户名查询用户信息  用户下的角色，角色下的权限 5表关联查询 1:多关系映射
     *
     * @param username
     * @return
     */
    @Override
    public User findByUsername(String username) {
        return userDao.findByUsername(username);
    }

    @Override
    public List<Menu> findMenuByUsername(String username) {
        List<Menu> fristLevelMenu = menuDao.getHeadMenuByUsername(username);
        for (Menu levelMenu : fristLevelMenu) {
            Integer parentId = levelMenu.getId();
            List<Menu> childrenMenu = menuDao.findMenuByParentId(parentId);
            levelMenu.setChildren(childrenMenu);
        }

        return fristLevelMenu;
    }

    @Override
    public PageResult<User> findByPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        if (!StringUtils.isEmpty(queryPageBean.getQueryString())) {
            queryPageBean.setQueryString("%" + queryPageBean.getQueryString() + "%");
        }
        Page<User> userPage = userDao.findByPage(queryPageBean.getQueryString());

        Long total = userPage.getTotal();
        List<User> rows = userPage.getResult();

        return new PageResult<User>(total, rows);
    }

    @Override
    public User findById(int id) {
        try {
            User user = userDao.findById(id);
            String date = DateUtils.parseDate2String(user.getBirthday());
            user.setDate(date);
            return user;
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyException("查询信息失败，请重新尝试");
        }
    }

    @Override
    public List<Integer> findRoleIdsByUserId(int id) {
        return userDao.findRoleIdsByUserId(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(User user, Integer[] roleIds) {
        try {
            Date birthday = DateUtils.parseString2Date(user.getDate());
            user.setBirthday(birthday);
            userDao.update(user);
            //删除用户与角色的旧关系
            userDao.deleteUserRole(user.getId());
            //循环添加用户与角色的关系
            for (Integer roleId : roleIds) {
                userDao.addUserRole(user.getId(), roleId);
            }
        } catch (Exception e) {
            e.printStackTrace();
			throw new MyException("修改信息失败，请重新尝试");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(User user, Integer[] roleIds) {
        try {
            Date birthday = DateUtils.parseString2Date(user.getDate());
            user.setBirthday(birthday);
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            String password = encoder.encode("1234");
            user.setPassword(password);
            userDao.add(user);
            for (Integer roleId : roleIds) {
                userDao.addUserRole(user.getId(), roleId);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyException("添加失败");
        }
    }

    @Override
    public void deleteById(int id) {
        userDao.deleteUserRole(id);
        userDao.delete(id);
    }

    @Override
    @Transactional(rollbackFor = MyException.class)
    public void updatePassword(Map<String, Object> map,int id) {
        String password = userDao.findPasswordById(id);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String firstNewPassword = (String) map.get("firstNewPassword");
        if (encoder.matches(firstNewPassword, password)) {
            throw new MyException("新密码不能与旧密码一致");
        }
        String newPassword = encoder.encode(firstNewPassword);
        userDao.updatePassword(newPassword, id);
    }

    @Override
    public void resetById(int id) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String password = encoder.encode("6666");
        userDao.updatePassword(password,id);
    }
}